package org.nmgyjt.springboot.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class IDAASAESUtils {

    public static final String AES_KEY = "6H3KYrLPpPN0fEhXeXCbbNUejwyJqwGf";
    private static final String AES_ALGORITHM_NAME = "AES/ECB/PKCS5Padding";
    private static final String ENCRYPT_TYPE = "AES";

    /**
     * 加密函数
     *
     * @param content 需要加密的内容
     * @return 加密后的byte[]
     */
    public static byte[] encrypt(String content, String aesKey) {
        try {
            byte[] secretSrc = content.getBytes(StandardCharsets.UTF_8);
            Cipher cipher = Cipher.getInstance(AES_ALGORITHM_NAME);
            SecretKey keySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), ENCRYPT_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            return cipher.doFinal(secretSrc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
//        String base64Encode = Base64.getEncoder().encodeToString(encrypt("{\"action\":\"verify\",\"password\":\"113456\",\"encrypted\":\"123456\",\"salt\":\"\",\"requestId\":\"22a0fc39-dcd5-426b-8a16-82898bf6521b\"}", AES_KEY));
//
//        System.out.println(base64Encode);

        String base64Encode = "rjKfrPfurTmiGirIstZBeQp37YI86fGCXJiVJN8Yr2g=";

        String src = decrypt(Base64.getDecoder().decode(base64Encode), AES_KEY);

        System.out.println(src);
    }

    /**
     * 解密函数
     *
     * @param cypherBytes 加密后的byte数组
     * @return 解密后的内容
     */
    public static String decrypt(byte[] cypherBytes, String aesKey) {
        try {
            Cipher cipher = Cipher.getInstance(AES_ALGORITHM_NAME);
            SecretKey keySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), ENCRYPT_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            return new String(cipher.doFinal(cypherBytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
